"""
数据库初始化数据模块
提供字典数据和基础数据的初始化功能
"""

import uuid
from datetime import datetime, date
from sqlalchemy.orm import Session
from .models import Dictionary, Asset, OobManagement, OperatingSystem, BusinessSystem, Middleware, IpManagement, Account

def generate_uuid():
    """生成UUID字符串"""
    return str(uuid.uuid4())

def init_dictionary_data(session: Session):
    """初始化字典数据"""
    
    # 设备资产类型
    asset_types = [
        Dictionary(
            dict_id='DICT_ASSET_001',
            dict_type='asset_type',
            dict_code='SERVER',
            dict_name='服务器',
            is_system=True,
            sort_order=1
        ),
        Dictionary(
            dict_id='DICT_ASSET_002',
            dict_type='asset_type',
            dict_code='SECURITY_DEVICE',
            dict_name='安全设备',
            is_system=True,
            sort_order=2
        ),
        Dictionary(
            dict_id='DICT_ASSET_003',
            dict_type='asset_type',
            dict_code='VM_PLATFORM',
            dict_name='虚拟机管理平台',
            is_system=True,
            sort_order=3
        ),
        Dictionary(
            dict_id='DICT_ASSET_004',
            dict_type='asset_type',
            dict_code='DISTRIBUTED_STORAGE',
            dict_name='分布式存储',
            is_system=True,
            sort_order=4
        ),
        Dictionary(
            dict_id='DICT_ASSET_005',
            dict_type='asset_type',
            dict_code='PC',
            dict_name='PC机',
            is_system=True,
            sort_order=5
        )
    ]
    
    # 业务系统类型
    system_types = [
        Dictionary(
            dict_id='DICT_SYS_001',
            dict_type='system_type',
            dict_code='OA',
            dict_name='OA系统',
            is_system=True,
            sort_order=1
        ),
        Dictionary(
            dict_id='DICT_SYS_002',
            dict_type='system_type',
            dict_code='FIREWALL_MGMT',
            dict_name='防火墙管理系统',
            is_system=True,
            sort_order=2
        ),
        Dictionary(
            dict_id='DICT_SYS_003',
            dict_type='system_type',
            dict_code='WAF',
            dict_name='WAF系统',
            is_system=True,
            sort_order=3
        ),
        Dictionary(
            dict_id='DICT_SYS_004',
            dict_type='system_type',
            dict_code='STORAGE_MGMT',
            dict_name='分布式存储管理系统',
            is_system=True,
            sort_order=4
        ),
        Dictionary(
            dict_id='DICT_SYS_005',
            dict_type='system_type',
            dict_code='VM_MGMT',
            dict_name='虚拟机管理平台系统',
            is_system=True,
            sort_order=5
        )
    ]
    
    # 中间件类型
    mw_types = [
        Dictionary(
            dict_id='DICT_MW_001',
            dict_type='mw_type',
            dict_code='DATABASE',
            dict_name='数据库',
            is_system=True,
            sort_order=1
        ),
        Dictionary(
            dict_id='DICT_MW_002',
            dict_type='mw_type',
            dict_code='CACHE',
            dict_name='缓存',
            is_system=True,
            sort_order=2
        ),
        Dictionary(
            dict_id='DICT_MW_003',
            dict_type='mw_type',
            dict_code='WEB_SERVER',
            dict_name='Web发布',
            is_system=True,
            sort_order=3
        ),
        Dictionary(
            dict_id='DICT_MW_004',
            dict_type='mw_type',
            dict_code='MESSAGE_QUEUE',
            dict_name='消息队列',
            is_system=True,
            sort_order=4
        )
    ]
    
    # 用途类型
    purposes = [
        Dictionary(
            dict_id='DICT_PURPOSE_001',
            dict_type='purpose',
            dict_code='CLINICAL',
            dict_name='临床',
            is_system=True,
            sort_order=1
        ),
        Dictionary(
            dict_id='DICT_PURPOSE_002',
            dict_type='purpose',
            dict_code='BUSINESS',
            dict_name='业务',
            is_system=True,
            sort_order=2
        ),
        Dictionary(
            dict_id='DICT_PURPOSE_003',
            dict_type='purpose',
            dict_code='ADMIN',
            dict_name='行政',
            is_system=True,
            sort_order=3
        ),
        Dictionary(
            dict_id='DICT_PURPOSE_004',
            dict_type='purpose',
            dict_code='MGMT_NETWORK',
            dict_name='管理网络',
            is_system=True,
            sort_order=4
        ),
        Dictionary(
            dict_id='DICT_PURPOSE_005',
            dict_type='purpose',
            dict_code='INTERNAL_COMM',
            dict_name='内部通信',
            is_system=True,
            sort_order=5
        ),
        Dictionary(
            dict_id='DICT_PURPOSE_006',
            dict_type='purpose',
            dict_code='BUSINESS_NETWORK',
            dict_name='业务网络',
            is_system=True,
            sort_order=6
        )
    ]
    
    # 状态类型
    statuses = [
        Dictionary(
            dict_id='DICT_STATUS_001',
            dict_type='status',
            dict_code='ENABLED',
            dict_name='启用',
            is_system=True,
            sort_order=1
        ),
        Dictionary(
            dict_id='DICT_STATUS_002',
            dict_type='status',
            dict_code='DISABLED',
            dict_name='禁用',
            is_system=True,
            sort_order=2
        )
    ]
    
    # 分配时长
    durations = [
        Dictionary(
            dict_id='DICT_DURATION_001',
            dict_type='allocation_duration',
            dict_code='PERMANENT',
            dict_name='永久',
            is_system=True,
            sort_order=1
        ),
        Dictionary(
            dict_id='DICT_DURATION_002',
            dict_type='allocation_duration',
            dict_code='ONE_MONTH',
            dict_name='1个月',
            is_system=True,
            sort_order=2
        ),
        Dictionary(
            dict_id='DICT_DURATION_003',
            dict_type='allocation_duration',
            dict_code='THREE_MONTHS',
            dict_name='3个月',
            is_system=True,
            sort_order=3
        ),
        Dictionary(
            dict_id='DICT_DURATION_004',
            dict_type='allocation_duration',
            dict_code='TEMPORARY',
            dict_name='临时',
            is_system=True,
            sort_order=4
        )
    ]
    
    # 关联类型
    relation_types = [
        Dictionary(
            dict_id='DICT_RELATION_001',
            dict_type='relation_type',
            dict_code='OOB',
            dict_name='带外系统',
            is_system=True,
            sort_order=1
        ),
        Dictionary(
            dict_id='DICT_RELATION_002',
            dict_type='relation_type',
            dict_code='OS',
            dict_name='操作系统',
            is_system=True,
            sort_order=2
        ),
        Dictionary(
            dict_id='DICT_RELATION_003',
            dict_type='relation_type',
            dict_code='SYSTEM',
            dict_name='业务系统',
            is_system=True,
            sort_order=3
        ),
        Dictionary(
            dict_id='DICT_RELATION_004',
            dict_type='relation_type',
            dict_code='MIDDLEWARE',
            dict_name='中间件',
            is_system=True,
            sort_order=4
        )
    ]
    
    # VLAN类型
    vlans = [
        Dictionary(
            dict_id='DICT_VLAN_001',
            dict_type='vlan',
            dict_code='VLAN10',
            dict_name='VLAN10',
            is_system=True,
            sort_order=1
        ),
        Dictionary(
            dict_id='DICT_VLAN_002',
            dict_type='vlan',
            dict_code='VLAN20',
            dict_name='VLAN20',
            is_system=True,
            sort_order=2
        ),
        Dictionary(
            dict_id='DICT_VLAN_003',
            dict_type='vlan',
            dict_code='VLAN30',
            dict_name='VLAN30',
            is_system=True,
            sort_order=3
        ),
        Dictionary(
            dict_id='DICT_VLAN_004',
            dict_type='vlan',
            dict_code='VLAN_CLINIC',
            dict_name='临床VLAN',
            is_system=True,
            sort_order=4
        ),
        Dictionary(
            dict_id='DICT_VLAN_005',
            dict_type='vlan',
            dict_code='VLAN_ADMIN',
            dict_name='管理VLAN',
            is_system=True,
            sort_order=5
        )
    ]
    
    # 合并所有字典数据
    all_dicts = asset_types + system_types + mw_types + purposes + statuses + durations + relation_types + vlans
    
    # 批量插入字典数据
    for dict_item in all_dicts:
        session.add(dict_item)
    
    session.commit()
    print(f"已初始化 {len(all_dicts)} 条字典数据")

def init_sample_data(session: Session):
    """初始化示例数据"""
    
    # 创建示例安全设备（先创建，以便服务器可以引用它）
    security_asset = Asset(
        asset_id=generate_uuid(),
        asset_type='SECURITY_DEVICE',
        asset_name='防火墙设备',
        asset_code='FW-001',
        model='Fortinet FortiGate 600E',
        cpu_cores=8,
        memory_gb=16.0,
        storage_capacity=500.0,
        hard_disk_count=2,
        hard_disk_specs='250GB SSD RAID 1',
        department='IT部门',
        purpose_desc='网络安全防护设备'
    )
    session.add(security_asset)
    
    # 创建示例服务器资产（引用安全设备作为其组成）
    server_asset = Asset(
        asset_id=generate_uuid(),
        asset_type='SERVER',
        asset_name='主应用服务器',
        asset_code='SRV-001',
        model='Dell PowerEdge R740',
        device_composition=f'["{security_asset.asset_id}"]',  # JSON数组格式，存储组成设备的asset_id
        cpu_cores=32,
        memory_gb=128.0,
        storage_capacity=2000.0,
        hard_disk_count=4,
        hard_disk_specs='1TB SSD RAID 5',
        department='IT部门',
        purpose_desc='主要业务应用服务器'
    )
    session.add(server_asset)
    
    session.commit()
    
    # 为服务器创建操作系统
    server_os = OperatingSystem(
        os_id=generate_uuid(),
        asset_id=server_asset.asset_id,
        os_name='Windows Server',
        version='2019 Standard',
        install_dir='C:\\Windows',
        install_date=date(2023, 1, 15)
    )
    session.add(server_os)
    
    # 为服务器创建带外管理
    server_oob = OobManagement(
        oob_id=generate_uuid(),
        asset_id=server_asset.asset_id,
        login_url='https://192.168.1.100'
    )
    session.add(server_oob)
    
    session.commit()
    
    # 创建中间件
    middleware_db = Middleware(
        mw_id=generate_uuid(),
        os_id=server_os.os_id,
        mw_type='DATABASE',
        name='MySQL',
        version='8.0.28',
        install_dir='C:\\MySQL',
        port=3306,
        config_file='C:\\MySQL\\my.ini'
    )
    session.add(middleware_db)
    
    middleware_cache = Middleware(
        mw_id=generate_uuid(),
        os_id=server_os.os_id,
        mw_type='CACHE',
        name='Redis',
        version='6.2.6',
        install_dir='C:\\Redis',
        port=6379,
        config_file='C:\\Redis\\redis.conf'
    )
    session.add(middleware_cache)
    
    session.commit()
    
    # 创建业务系统
    business_system = BusinessSystem(
        system_id=generate_uuid(),
        system_type='OA',
        system_name='办公自动化系统',
        description='企业办公自动化管理系统',
        负责人='张三',
        department='行政部',
        os_id=server_os.os_id
    )
    session.add(business_system)
    
    session.commit()
    
    # 关联中间件到业务系统
    from .models import SystemMiddleware
    system_mw = SystemMiddleware(
        system_id=business_system.system_id,
        mw_id=middleware_db.mw_id
    )
    session.add(system_mw)
    
    # 创建IP地址
    ip_server = IpManagement(
        ip='192.168.1.100',
        subnet_mask='255.255.255.0',
        vlan='VLAN20',
        purpose='BUSINESS',
        status='ENABLED',
        allocation_duration='PERMANENT',
        asset_id=server_asset.asset_id,
        hostname='SRV-001',
        description='主应用服务器IP'
    )
    session.add(ip_server)
    
    ip_oob = IpManagement(
        ip='192.168.10.100',
        subnet_mask='255.255.255.0',
        vlan='VLAN_ADMIN',
        purpose='MGMT_NETWORK',
        status='ENABLED',
        allocation_duration='PERMANENT',
        oob_id=server_oob.oob_id,
        hostname='SRV-001-OOB',
        description='服务器带外管理IP'
    )
    session.add(ip_oob)
    
    ip_database = IpManagement(
        ip='192.168.1.101',
        subnet_mask='255.255.255.0',
        vlan='VLAN20',
        purpose='BUSINESS',
        status='ENABLED',
        allocation_duration='PERMANENT',
        mw_id=middleware_db.mw_id,
        hostname='SRV-001-DB',
        description='MySQL数据库IP'
    )
    session.add(ip_database)
    
    session.commit()
    
    # 创建账号
    from ..utils.crypto import encrypt_password
    
    # 服务器账号
    account_server = Account(
        account_id=generate_uuid(),
        relation_type='OS',
        relation_id=server_os.os_id,
        username='administrator',
        encrypted_password=encrypt_password('Admin@123'),
        role='管理员',
        valid_from=date(2023, 1, 15),
        description='服务器管理员账号'
    )
    session.add(account_server)
    
    # 带外管理账号
    account_oob = Account(
        account_id=generate_uuid(),
        relation_type='OOB',
        relation_id=server_oob.oob_id,
        username='admin',
        encrypted_password=encrypt_password('Admin@123'),
        role='管理员',
        valid_from=date(2023, 1, 15),
        description='带外管理管理员账号'
    )
    session.add(account_oob)
    
    # 数据库账号
    account_db = Account(
        account_id=generate_uuid(),
        relation_type='MIDDLEWARE',
        relation_id=middleware_db.mw_id,
        username='root',
        encrypted_password=encrypt_password('Db@123'),
        role='管理员',
        valid_from=date(2023, 1, 15),
        description='MySQL数据库管理员账号'
    )
    session.add(account_db)
    
    session.commit()
    print("已初始化示例数据")

def initialize_all_data(session: Session):
    """初始化所有数据"""
    try:
        # 检查是否已有字典数据
        from sqlalchemy import select
        dict_count = session.execute(select(Dictionary)).scalars().all()
        if len(dict_count) == 0:
            init_dictionary_data(session)
            init_sample_data(session)
            print("数据库初始化完成")
        else:
            print("数据库已存在数据，跳过初始化")
    except Exception as e:
        session.rollback()
        print(f"数据初始化失败: {e}")
        raise